/**
 * Created by tang on 2018/3/27.
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  TreeSelect, Form, Input, DatePicker, Select, Button, notification, Card, InputNumber, Radio,
  Icon, Tooltip, Upload, Modal, Pagination,message
} from 'antd';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
//const { TextArea } = Input;
const Option = Select.Option;
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import styles from './BannerAdd.less';
import  Editor  from '@/components/Ueditor/Ueditor';
const FormItem = Form.Item;
import queryString from 'query-string';
import { urlAction } from '../../utils/global';
//import EditorConvertToHTML from '../../components/Editor/Editor';

@connect(state => ({
  banner: state.banner
}))
@Form.create()

export default class BannerAdd extends PureComponent {

  state = {
    type1:0,
    isEditor:0, // 0 显示富文本  1 不显示
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "banner/clear"
    });
    var search = queryString.parse(this.props.location.search);
    if (search.id) { //修改
      dispatch({
        type: 'banner/save',
        payload: {
          id: search.id,
        }
      });
      dispatch({
        type: 'banner/toUpdate',
        payload: {id: search.id},

      });
      //console.log(this.state.type1)
      setTimeout(()=>{
        //console.log("11111",this.state.type1)
        const { banner } = this.props;
        const { type } = banner;
        this.setState({
          type1:type
        });
        this.onType(this.state.type1)
      },1000);



    }
  }

  onInputChange(e){
    var key = e.target.name;
    var value = e.target.value;
    const { dispatch } = this.props;
    var t = {};
    t[key] = value;
    dispatch({
      type: 'banner/save',
      payload: t
    })
  }

  onInputNumChange(key, value){
    var t = {};
    t[key] = value;
    this.props.dispatch({
      type: 'banner/save',
      payload: t
    })
  }

  onType(value){


    this.props.dispatch({
      type:'banner/save',
      payload:{
        type:value
      }
    });
    this.setState({
      type1:value
    });

     if(value === "1"){
      //外链
      this.setState({
        isEditor:0
      });
      // 组件卸载后，清除放入库的id
    }else if(value == "0"){
      //无连接
      this.setState({
        isEditor:0
      })
    }

  }

  btnAct(){
    const {dispatch} = this.props;
    const {banner} = this.props;
    const {img, sort, id, type, url, content} = banner;
    var data;
    dispatch({
      type: 'banner/save',
      payload: {submitting: true}
    });
    if (id){
      data = { img, type, sort, id, url,content};

      if(!img){
        message.error("请选择图片");
        dispatch({
          type: 'banner/save',
          payload: {submitting: false}
        });
      }else if(type == 1 && url == ''){
        message.error("请填写外链");
        dispatch({
          type: 'banner/save',
          payload: {submitting: false}
        });
      }else if(type == 1 && url){
        dispatch({
          type: "banner/update",
          payload: {
            img:img,
            type:type,
            url:url,
            content:'',
            sort:sort,
            id:id
          }
        })
      }else if(type == 0){
        dispatch({
          type: "banner/update",
          payload: {
            img:img,
            type:type,
            url:'',
            content:'',
            sort:sort,
            id:id
          }
        })
      }

    } else {
      data = {img, type, url, sort,content};
      if(!img){
        message.error("请选择图片");
        dispatch({
          type: 'banner/save',
          payload: {submitting: false}
        });
      }else if(type == 1 && url == ''){
        message.error("请填写外链");
        dispatch({
          type: 'banner/save',
          payload: {submitting: false}
        });
      }else if(type == 1 && url){
        dispatch({
          type: "banner/add",
          payload: {
            img:img,
            type:type,
            url:url,
            content:'',
            sort:sort
          }
        });

      }else if(type == 0){
        dispatch({
          type: "banner/add",
          payload: {
            img:img,
            type:type,
            url:'',
            content:'',
            sort:sort,
            id:id
          }
        })
      }
    }
  };

  //图片
  handleCancel() {
    const {dispatch} = this.props;
    dispatch({
      type: 'banner/save',
      payload: {previewVisible: false}
    })
  }

  handlePreview(file) {
    const {dispatch} = this.props;
    dispatch({
      type: 'banner/save',
      payload: {
        previewImage: file.url || file.thumbUrl,
        previewVisible: true,
      }
    });
  }

  handleChanges(fileList) {
    const {dispatch} = this.props;
    dispatch({
      type: "banner/save",
      payload: {fileList: fileList.fileList}
    });
    var file = fileList.fileList[0];
    var fileRemoved = fileList.file;
    if (file){
      if (file.status === 'done') {
        var fileName = file.response.body.fileName;
        dispatch({
          type: "banner/save",
          payload: {img: fileName}
        });
      }
    } else if (fileRemoved.status === "removed"){
      dispatch({
        type: "banner/save",
        payload: {img: ""}
      });
    }
  }


  render() {
    const {  banner } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { img,sort,previewVisible,previewImage,fileList, id , url,submitting,type,content} = banner;



    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className={styles.ant_upload_text}>Upload</div>
      </div>
    );

    var formItemArray = [];
    var keyArray = ["img", "sort", "type","url"];
    var valueArray = [img, sort,type, url];
    var labelArray = ["图片", "排序", "类型","外链"];


    for (var i = 0; i<keyArray.length; i++){
      var itemKey = labelArray[i] + "不能为空";
      switch (i){
        case 0: //图片
          formItemArray.push(
            <FormItem
              key={"news-item-" + i}
              {...formItemLayout}
              label={labelArray[i]}
            >
              {getFieldDecorator(keyArray[i], {
                rules: [{
                  required: true, message: itemKey,
                }],
                initialValue: valueArray[i]
              })(
                <div>
                  <Upload
                    action={urlAction}
                    listType="picture-card"
                    fileList={fileList}
                    accept="image/jpeg,image/jpg"
                    data={{projectName:'blockchain', thumbnail_size: 1000}}
                    onPreview={this.handlePreview.bind(this)}
                    onChange={this.handleChanges.bind(this)}
                  >
                    {fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                  (图片比例为3:1)
                  <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel.bind(this)}>
                    <img className={styles.look_large_img} alt="example" src={previewImage}/>
                  </Modal>
                </div>
              )}
            </FormItem>
          );
          break;
        case 1://sort
          formItemArray.push(
            <FormItem
              key={"news-item-" + i}
              {...formItemLayout}
              label={labelArray[i]}
            >
              {getFieldDecorator(keyArray[i], {
                rules: [{
                  required: true, message: itemKey,
                }],
                initialValue: valueArray[i]
              })(
                <InputNumber min={0} className={styles.full_witdh} name="sort" placeholder="请输入排序" onChange={this.onInputNumChange.bind(this, "sort")} />
              )}
            </FormItem>
          );
          break;
        case 2://类型
          formItemArray.push(
            <FormItem
              key={"news-item-" + i}
              {...formItemLayout}
              label={labelArray[i]}
            >

              <Select
                value={this.state.type1+''}
                style={{ width: 120 }}
                onChange={this.onType.bind(this)}>
                <Option value="0">无链接</Option>
                <Option value="1">外链</Option>
              </Select>

            </FormItem>
          );
              break;
        case 3://外链

          if(type == 2){
            formItemArray.push(
              <FormItem
                key={"banner-link-" + i}
                {...formItemLayout}
                label={labelArray[i]}
              >
                {getFieldDecorator(keyArray[i], {
                  rules: [{
                    required: false, message: itemKey
                  }],
                  initialValue: valueArray[i]
                })(
                  <Input maxLength="50" name={keyArray[i]} onChange={this.onInputChange.bind(this)} placeholder={"请输入以http://或https://开头的链接"} />
                )}
              </FormItem>
            );
          }
          break;
        default:

          break;
      }
    }


    return (
      <PageHeaderLayout title={id?"修改轮播图":"添加轮播图"} content="">
        <Card bordered={false}>

          <Form
            hideRequiredMark
            style={{ marginTop: 8 }}
          >
            {formItemArray}
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" onClick={this.btnAct.bind(this)} loading={submitting}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
